package com.cookbook.controller;

import com.cookbook.RequestAuthority;
import com.cookbook.Result;
import com.cookbook.database.model.User;
import com.cookbook.service.ShareService;
import com.cookbook.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * @author 毛川
 */
@Controller
@RequestMapping("/user")
@SessionAttributes("user")
public class UserController {

    @Autowired
    private ShareService shareService;

    @RequestAuthority
    @Transactional
    @RequestMapping("/info")
    @ResponseBody
    public String information(@ModelAttribute User user) {
        if (user == null) {
            return Result.format(Result.INTERNAL_ERROR, "内部错误");
        }
        user.setPassword(null);
        return Result.success(user);
    }

    @RequestAuthority
    @Transactional
    @RequestMapping("/shares")
    @ResponseBody
    public String shares(
            @ModelAttribute User user,
            @RequestParam Integer page,
            @RequestParam Integer limit) {
        if (user == null)
            return Result.format(Result.INTERNAL_ERROR, "内部错误");
        if (page < 0 || limit < 0) {
            return Result.format(Result.PARAMETER_INVALID, "非法参数");
        }
        try {
            return Result.success(shareService.selectMyShare(user, page, limit));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.format(Result.INTERNAL_ERROR, "内部错误");
        }
    }
}
